package com.shenbianyun.youfu;


import com.alibaba.fastjson.JSONObject;
import com.shenbianyun.bosskgpay.entity.RequestMessage;
import com.shenbianyun.bosskgpay.entity.pay.PaymentReqModel;
import com.shenbianyun.bosskgpay.utils.*;
import com.shenbianyun.youfu.entity.PaymentQuery;
import com.shenbianyun.youfu.entity.RequestMsg;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;



/**
 * @Description //Jmeter 优付的批量付款 接口：30481
 * 不可固定业务参数
 **/

public class OnlinePaymentQueryServiceYoufuJ extends AbstractJavaSamplerClient {


    public final String CHARSET_UTF_8 = "UTF-8";

    public final String INTER_KEY = "f51e85936b6142c29404aa1df1fa54bc";
    public static String MER_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIOnkbqyoQbO/PUtfBa+540mweQSqp5CMQG17IliFflsiIsDWHOz4z6T6HoK+0ecXDKBD6d0udH2/3oaGP0fWh5foM+Gc7MMkQcJxicxSqeSQjJuY4NodpURZlHWeQyPcVAUSRnpV89gQv4hVmr3r8y+pDBLJXZO7LUSm3l0OA9JAgMBAAECgYAlos6vL4eG+b8om9MgcXyiRlUhTRDHYya9VXOEJq0fe55hFxi/Isqwxfmsgd0psJJOwcRm26CPXGvWTQWdvsu0/kk0IH5nu3V1MtsxgWsrRBXj7x/9VSSsXUg5jQ/k0izoo3hl09nfnMOHcZtT0E/erEL/2cAzaRMPvlF5dn8SLQJBAN3dbuAK5MLY5TvGWzjXF680Ai9a2hPgmszG4V4nwjbECc/ofzLQ+hTVP2E0Bz215FrR/UlxFyK03MSVyFMtn1cCQQCX6QfWIaOkxnv1C9t8GO5pr/IdVruZBDNGppaI4t7/vWaecCL0uwK7uD1nGeJ3qvgym1zumephaBwPiFbEhsJfAkBYa/LPWagYO6cIbqJWgerPibPBOb0mJOKs8CpLgx71AqZCdQ+UqhKxENgEnl6waniK9ZuzlF27GEfQFT3UYJ9bAkEAldOSlRHsktHo5FFjkswMKVUNmP44XL0VzbL0eeI5S0cE9XNoJrRkB725YfzXrmuEDHXLfNF1p8jFFFTGL2MyRQJASm/3l5ncQVN+S3gruo57gUtjHDnMugZxgtDR6oa0kL+Q9s/VwE27UHzA+Fh5DD1OMTDdTmlD9sIddtF3gvOhzQ==";
    public static String MER_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN0YKZY/NDGrrqNTwrVyvhKUmHeJCHlB2FUqrvsaH9I8kS3TkRvQyXnUwBEhNtLEZ1ryRaB0QnwPP7rM1DkMF6tLmqjonE6T++50m0CnvgAEg+JC08//Vy9qMJHR9zx/N5VMYzaRrqsrFCfwsYerYBSeOHltkAr8UiYfoguVK5ewIDAQAB";
    public static String YOU_FU_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN0YKZY/NDGrrqNTwrVyvhKUmHeJCHlB2FUqrvsaH9I8kS3TkRvQyXnUwBEhNtLEZ1ryRaB0QnwPP7rM1DkMF6tLmqjonE6T++50m0CnvgAEg+JC08//Vy9qMJHR9zx/N5VMYzaRrqsrFCfwsYerYBSeOHltkAr8UiYfoguVK5ewIDAQAB";
    public final String MER_ID = "89900003290117338190";
    public final String PROJECT_ID = "1610278112283347125";
    public final String API_VERSION = "V1.0";
    public final String OMS_TEST_URL = "http://47.108.253.203:8280/trans-business/clientBusiness/common.do";

    public static Long levy_id = 55007L;//30481L、35503L、35503L

    public RequestMessage rm;
    public PaymentReqModel.PayItems payItems;


    public String runOnlinePaymentQueryServiceYoufuJ() throws Exception {

        /**--------————————————业务请求参数——————————————————**/
        PaymentQuery paymentQuery = new PaymentQuery();
        //批次号：需和付款的批次号一致
        paymentQuery.setMerBatchId("920724010835116032");
        paymentQuery.setMerId(MER_ID);
        List<PaymentQuery.QueryItems> queryItemsList = new ArrayList<>();
        PaymentQuery.QueryItems queryItem = new PaymentQuery.QueryItems();
        //订单号：需和付款的订单号一致
        queryItem.setMerOrderId("OrderPay920724010835116032");
        queryItemsList.add(queryItem);
        paymentQuery.setQueryItems(queryItemsList);

        String json = JsonUtils.toJson(paymentQuery);
        //System.out.println("请求未加密数据:" + json);


        RequestMsg rm = new RequestMsg();
        rm.setFunCode("6002");
        rm.setMerId(MER_ID);
        rm.setVersion(API_VERSION);
        Long id = SnowflakeIdGeneratorFactory.getInstance().nextId();
        rm.setReqId(id + "");
        //加密处理
        byte[] bs = DESUtils.encrypt(json.getBytes(CHARSET_UTF_8), INTER_KEY);
        String reqDataEncrypt = Base64Utils.encodeToString(bs);
        rm.setReqData(reqDataEncrypt);
        rm.setSign(RSAUtils.sign(reqDataEncrypt, MER_PRIVATE_KEY));
        String reqStr = JsonUtils.toJson(rm);
        //System.out.println("请求加密数据：" + reqStr);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("reqJson", reqStr);
        String resData = httpClientPost(OMS_TEST_URL, map);
        //System.out.println("响应数据：" + resData);

        return resData;
    }


    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult sampleResult = new SampleResult();
        String resData = "";

        try {
            sampleResult.sampleStart();

            resData = runOnlinePaymentQueryServiceYoufuJ();
            //System.out.println("reqdata：" + resData);

            // 通过下面的操作就可以将被测方法的响应输出到Jmeter的察看结果树中的响应数据里面了。
            //断言
            JSONObject jsonObject1 = JSONObject.parseObject(resData);
            if (jsonObject1.get("resCode").equals("0000")) {
                sampleResult.setResponseOK();
                sampleResult.setResponseData(true + "", SampleResult.TEXT);
                System.out.println("批量付款结果:" + true);
            } else {
                sampleResult.setSuccessful(false);
                sampleResult.setResponseData(false + " " + jsonObject1.get("resMsg"), SampleResult.TEXT);
                System.out.println("批量付款结果:" + false + " " + jsonObject1.get("resMsg"));
            }
        } catch (Exception e) {
            sampleResult.setSuccessful(false);
            sampleResult.setResponseData(resData, SampleResult.TEXT);
            sampleResult.setResponseMessage(e.toString());
        } finally {
            sampleResult.sampleEnd();
        }

        return sampleResult;
    }

    private static String getHttpResult(InputStream httpInputStream, String charset) throws IOException {
//		return IOUtils.toString(new BufferedReader(new InputStreamReader(httpInputStream, charset)));
        String readLine;
        // 当正确响应时处理数据
        StringBuffer resultBuffer = new StringBuffer();

        try (
                // 处理响应流，必须与服务器响应流输出的编码一致
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpInputStream, charset))) {
            while ((readLine = responseReader.readLine()) != null) {
                resultBuffer.append(readLine);
            }
        }
        return resultBuffer.toString();
    }

    public static CloseableHttpClient client = HttpClients.custom()
            .setMaxConnPerRoute(50)
            .setMaxConnTotal(200)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setSocketTimeout(10000)
                    .build())
            .setKeepAliveStrategy((response, context) -> 15 * 1000) // 设置Keepalive的时间为60s→2023-9-11 尝试规避NoHttpResponseException，与红洁/海鹏沟通，改为<60s
            .build();

    public static String httpClientPost(String urlParam, Map<String, Object> params ) {

        HttpPost httpPost = new HttpPost(urlParam);
        String charset = "UTF_8";
        Object token = params.get("token");
        // 构建请求参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> elem = iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
        }
        try {
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = client.execute(httpPost);
            // 读取服务器响应数据
            return getHttpResult(response.getEntity().getContent(), charset);
        } catch (Exception e) {
            Throwable cause = e.getCause();
            //单独处理“Caused by: org.apache.http.ProtocolException: Target host is not specified”，转换成人话
            if (cause instanceof org.apache.http.ProtocolException) {
//				System.out.println("-----------------"+ cause.getMessage());Target host is not specified
                throw new RuntimeException("请确保正确设置了目标主机的URL");
            }
            throw new RuntimeException(e);
        }
    }

    //public static void main(String[] args) {
    //    try {
    //        OnlinePaymentQueryServiceYoufuJ j = new OnlinePaymentQueryServiceYoufuJ();
    //        j.runOnlinePaymentQueryServiceYoufuJ();
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //    }
    //}

}
